package com.coffee.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.common.service.RedisService;
import com.coffee.admin.api.login.request.ForgetByPasswordReq;
import com.coffee.admin.api.login.request.ForgetBySmsReq;
import com.coffee.admin.api.login.request.LoginByPasswordRequert;
import com.coffee.admin.api.login.request.LoginBySmsRequert;
import com.coffee.admin.api.merchant.req.RegisterReq;
import com.coffee.admin.api.merchant.service.MerchantService;
import com.coffee.core.anotation.LoginCheck;
import com.coffee.core.anotation.OperLog;
import com.coffee.core.entity.PassToken;
import com.coffee.core.entity.SiteContextThreadLocal;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.result.Result;
import com.coffee.core.util.PasswordUtil;
import com.coffee.core.util.ToolMobileSegmentResult;
import com.coffee.core.util.WebUtil;
import com.coffee.core.util.ZhongtailClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 登录控制层
 **/
@RestController
@RequestMapping("/merchant")
public class LoginController {
    private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    @DubboReference(check = false)
    private MerchantService merchantService;

    @DubboReference(check = false)
    private RedisService redisService;

    @PostMapping(value = "/register")
    @OperLog(operModul = "登录模块", operDesc = "注册账号")
    public Result<Integer> register(@RequestBody RegisterReq req, HttpServletRequest request, HttpServletResponse response) {
        String password = req.getPassword();
        try {
            ValidateBusinessException.assertStringNotBlank(password, ExceptionEnum.ERROR_1202);
            req.setPassword(PasswordUtil.getPass(password));
            LOG.info("注册：" + JSONObject.toJSONString(req));
            ToolMobileSegmentResult mobileSeg = ZhongtailClient.getMobileSeg(req.getMobile());
            req.setCity(mobileSeg.getCity());
            req.setProvince(mobileSeg.getProvince());
            String token = merchantService.register(req);
            WebUtil.addCookie(response, "ctoken", token);
            return Result.success(1);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }

    }

    /**
     * @Description: 用户密码登录
     */
    @PostMapping(value = "/passwordLogin")
    @OperLog(operModul = "登录模块", operDesc = "密码登录")
    public Result<String> passwordLogin(@RequestBody LoginByPasswordRequert req, HttpServletRequest request, HttpServletResponse response) {
        String token = null;
        try {
            token = merchantService.passwordLogin(req);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        WebUtil.addCookie(response, "ctoken", token);
        return Result.success(token);
    }

    @OperLog(operModul = "登录模块", operDesc = "验证码登录")
    @PostMapping(value = "/smsLogin")
    public Result<String> smsLogin(@RequestBody LoginBySmsRequert req, HttpServletRequest request, HttpServletResponse response) {
        String token = null;
        try {
            token = merchantService.smsLogin(req);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        WebUtil.addCookie(response, "ctoken", token);
        return Result.success(token);
    }

    /***
     * @Description: 退出登录
     */
    @OperLog(operModul = "登录模块", operDesc = "退出登录")
    @LoginCheck
    @PostMapping(value = "/logout")
    public Result<String> logout(HttpServletResponse response) {
        PassToken passToken = SiteContextThreadLocal.get();
        String ctoken = passToken.getCtoken();
        if (StringUtils.isNotEmpty(ctoken)) {
            WebUtil.deleteCookie(response, "ctoken");
            passToken.setCtoken(null);
            SiteContextThreadLocal.set(passToken);
            redisService.del(ctoken);
        }

        return Result.success("退出登录成功");
    }


    @OperLog(operModul = "手机验证码修改密码", operDesc = "手机验证码修改密码")
    @PostMapping(value = "/sms/forgetPassword")
    public Result<String> forgetPassword(@RequestBody ForgetBySmsReq req, HttpServletResponse response) {
        String password = req.getPassword();
        req.setPassword(PasswordUtil.getPass(password));
        try {
            ValidateBusinessException.assertStringNotBlank(password, ExceptionEnum.ERROR_1202);
            merchantService.forgetBySmsReq(req);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        return Result.success("退出登录成功");
    }


    @OperLog(operModul = "手机验证码修改密码", operDesc = "旧密码修改密码")
    @LoginCheck
    @PostMapping(value = "/password/forgetPassword")
    public Result<String> forgetPasswordByPassword(@RequestBody ForgetByPasswordReq req, HttpServletResponse response) {
        String oldPassword = req.getOldPassword();
        String newPassword = req.getNewPassword();
        try {
            ValidateBusinessException.assertStringNotBlank(oldPassword, ExceptionEnum.ERROR_1225);
            ValidateBusinessException.assertStringNotBlank(newPassword, ExceptionEnum.ERROR_1219);
            merchantService.forgetByPasswordReq(req);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        return Result.success("退出登录成功");
    }

    @PostMapping(value = "/updateMerchantCity")
    public Result<String> updateMerchantCity(HttpServletResponse response) {
        try {
            merchantService.updateMerchantCity();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success("城市修改成功");
    }

}
